/******************************************************************************
File: FuncBO.java

Version 1.0
Date            Author                Changes
Jan.26,2004     PO tools              Created

Copyright (c) 2003, Vanda Group.
all rights reserved.
******************************************************************************/
package com.vandagroup.portal.func;

import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import com.vandagroup.common.bean.BaseBean;
import com.vandagroup.common.bo.ESSBO;
import com.vandagroup.common.po.ESSTransaction;
import com.vandagroup.common.util.DataFormat;
import com.vandagroup.common.util.Result;
import com.vandagroup.common.util.SQLFormat;
import com.vandagroup.common.util.seqgener.KeyGen;
import com.vandagroup.portal.PortalParas;

/**
* This class is the Business Process Object interface
* 
* @see ess.base.bo.ESSBO
*/
public class FuncBO extends ESSBO {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * �K���K��ָ�K���K��Func�K���K��
	 */
	public int add(FuncFormBean bean) throws SQLException, Exception {
		String funcID = KeyGen.getKey("FUNC", 8);
		bean.setFuncID(funcID);
		bean.setLevelID(getLevelID(bean.getParentFuncID()));
		ESSTransaction trans = new ESSTransaction();
		trans.begin();

		FuncPO po = new FuncPO();
		bean.setIsLeaf(PortalParas.IS_LEAF);
		po.setFuncForm(bean);
		int rows = trans.add(po);

		if (!bean.getParentFuncID().equals("$$$$$$$$")) {
			rows += trans.executeUpdate("UPDATE FUNC SET ISLEAF = '"
					+ PortalParas.IS_BRANCH + "' WHERE FUNCID = '"
					+ bean.getParentFuncID() + "'");
		}

		// ��Ĭ�K���K��Ԍ���K���K���K���K���_��ϵ�y�K���K���_���K��
		trans
				.executeUpdate("INSERT INTO ORGFUNC(ORGID, FUNCID) VALUES('00000000', '"
						+ funcID + "')");
		trans
				.executeUpdate("INSERT INTO ORGROLEFUNC(ROLEID, FUNCID, ORGID) VALUES('00000000', '"
						+ funcID + "', '00000000')");

		trans.commit();
		return rows;
	}

	/**
	 * �h�K��ָ�K���K��Func�K���K��
	 */
	public int remove(FuncFormBean form) throws Exception {

		FuncPO po = new FuncPO();
		
		/*
		BaseBean[] baseBean = (BaseBean[]) po
				.query("WITH RPL ( FUNCID ) AS ( SELECT ROOT.FUNCID FROM FUNC ROOT WHERE ROOT.PARENTFUNCID = '"
						+ form.getFuncID()
						+ "' UNION ALL SELECT CHILD.FUNCID FROM RPL PARENT, FUNC CHILD WHERE PARENT.FUNCID = CHILD.PARENTFUNCID ) SELECT DISTINCT FUNCID FROM RPL ORDER BY FUNCID");
		String[] funcs = new String[baseBean.length];
		for (int i = 0; i < baseBean.length; i++) {
			funcs[i] = (String) baseBean[i].get("FUNCID");
		}*/
		

		List funcList = getBranchFunctionIds(form.getFuncID(), po) ;
		String[] funcs = (String[])funcList.toArray(new String[funcList.size()]) ;


		ESSTransaction trans = new ESSTransaction();
		trans.begin();

		po
				.setWhereClause("FUNCID = '"
						+ form.getFuncID()
						+ "' OR FUNCID IN ("
						+ (funcs.length == 0 ? "''" : SQLFormat.joinAsList(
								funcs, true)) + ")");
		int rows = trans.delete(po);

		if (!form.getParentFuncID().equals("00000000")) {
			rows += trans.executeUpdate("UPDATE FUNC SET ISLEAF = '"
					+ PortalParas.IS_LEAF + "' WHERE FUNCID = '"
					+ form.getParentFuncID() + "'");
		}
		trans
				.executeUpdate("delete from ORGFUNC where FUNCID ='"
						+ form.getFuncID()
						+ "' or FUNCID IN ("
						+ (funcs.length == 0 ? "''" : SQLFormat.joinAsList(
								funcs, true)) + ")");
		trans
				.executeUpdate("delete from ORGROLEFUNC where FUNCID ='"
						+ form.getFuncID()
						+ "' or FUNCID IN ("
						+ (funcs.length == 0 ? "''" : SQLFormat.joinAsList(
								funcs, true)) + ")");
		trans.commit();
		return rows;
	}

	private List getBranchFunctionIds(String rootId,FuncPO po) throws Exception {

		List result = new LinkedList() ;
		
		BaseBean[] baseBean = (BaseBean[]) po.query("SELECT FUNCID,ISLEAF  FROM FUNC WHERE PARENTFUNCID ='"+rootId+"'");

		for (int i = 0; i < baseBean.length; i++) {
			String funcId = (String) baseBean[i].get("FUNCID");
			result.add(funcId) ;
			
			if (!PortalParas.IS_LEAF.equals((String)baseBean[i].get("ISLEAF"))) {
			    result.addAll(getBranchFunctionIds(funcId, po)) ;
			}
		}
		
		return result ;
	}
	
	/**
	 * �K��ȡָ�K���K���K���K�Func�K���K��
	 */
	public Result retrieve(int pageNO) throws SQLException {
		FuncPO po = new FuncPO();

		po.setWhereClause("");
		po.setResultPage(Result.DEFAULT_PAGE_SIZE, pageNO);
		Result result = po.retrieveResult();
		return result;
	}

	public FuncFormBean retrieve(FuncFormBean form) throws SQLException {
		FuncPO po = new FuncPO();
		po.setFuncForm(form);
		po.setWhereClause("FUNCID = '" + form.getFuncID() + "'");
		return (FuncFormBean) po.retrieveForm();
	}

	/**
	 * �K���K��ָ�K���K��Func�K���K��
	 */
	public int update(FuncFormBean bean) throws SQLException {
		FuncPO po = new FuncPO();
		po.setWhereClause("FUNCID = '" + bean.getFuncID() + "'");
		po.setFuncForm(bean);
		int rows = po.update();
		return rows;
	}

	/**
	 * �K��ȡָ�K���K���K���K�Func�K���K��
	 */
	public Result retrieveList(int pageNO) throws SQLException, Exception {
		FuncPO po = new FuncPO();
		po.setResultPage(Result.DEFAULT_PAGE_SIZE, pageNO);
		Result result = po.retrieveResult();
		return result;
	}

	/**
	 * �K��ݸ�K���K��ܴ�K���K��K��δ�K���K�1�7
	 * 
	 * @param parentFuncID
	 * @return String
	 * @throws SQLException
	 * @throws Exception
	 *             Create Date : 2004-2-21
	 */
	public String getLevelID(String parentFuncID) throws SQLException,
			Exception {
		FuncPO po = new FuncPO();
		BaseBean baseBean = po
				.queryBean("SELECT RTRIM(LEVELID) LEVELID FROM FUNC WHERE FUNCID = '"
						+ parentFuncID + "'");
		String pLevelID = "";
		String maxLevelID = "";
		String levelID = "";
		if (baseBean != null) {
			pLevelID = (String) baseBean.get("LEVELID");
			baseBean = null;
			baseBean = po
					.queryBean("SELECT MAX(RTRIM(LEVELID)) LEVELID FROM FUNC WHERE LEVELID LIKE '"
							+ pLevelID
							+ "%' AND LENGTH(RTRIM(LEVELID)) = "
							+ (pLevelID.length() + 3));
			if (baseBean == null || baseBean.get("LEVELID") == null
					|| ((String) baseBean.get("LEVELID")).equals("")) {
				levelID = pLevelID + "001";
			} else {
				maxLevelID = (String) baseBean.get("LEVELID");
				levelID = pLevelID
						+ DataFormat.intToString(Integer.parseInt(maxLevelID
								.substring(maxLevelID.length() - 3, maxLevelID
										.length())) + 1, 3);
			}
		} else {
			baseBean = null;
			baseBean = po
					.queryBean("SELECT MAX(RTRIM(LEVELID)) LEVELID FROM FUNC WHERE LENGTH(RTRIM(LEVELID)) = 3");
			if (baseBean == null || baseBean.get("LEVELID") == null
					|| ((String) baseBean.get("LEVELID")).equals("")) {
				levelID = "001";
			} else {
				maxLevelID = (String) baseBean.get("LEVELID");
				levelID = DataFormat.intToString(Integer
						.parseInt(maxLevelID.substring(maxLevelID.length() - 3,
								maxLevelID.length())) + 1, 3);
			}
		}
		return levelID;
	}

	/**
	 * �K���K�where�K���KϵͻI���K��ܴ�K���K���K�U���K���K��sql�K���K�g��õ�K�in�K�Ӿ�
	 * 
	 * @param whereClause
	 * @return String
	 * @throws Exception
	 *             Create Date : 2004-2-25
	 */
	public String getFuncIDInClause(String whereClause) throws Exception {
		String rtn = "";
		String[] funcs = null;

		FuncPO po = new FuncPO();
		String sql = "SELECT FUNCID FROM FUNC WHERE FUNCID <> '$$$$$$$$'"
				+ (whereClause == null ? "" : " AND " + whereClause);
		System.out.println(sql);
		BaseBean[] baseBean = (BaseBean[]) po.query(sql);
		if (baseBean == null || baseBean.length == 0) {
			rtn = "''";
		} else {
			funcs = new String[baseBean.length + 1];
			for (int i = 0; i < baseBean.length; i++) {
				funcs[i] = (String) baseBean[i].get("FUNCID");
			}
			rtn = SQLFormat.joinAsList(funcs, true);
		}
		return rtn;
	}

}
